//index.js
//获取应用实例
const app = getApp()
import { getBase64ImgData} from '../../utils/getQrCode';

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    windowWidth:wx.getSystemInfoSync().windowWidth,
    windowHeight:wx.getSystemInfoSync().windowHeight,
    img:"",
    accessToken:""
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    // var scene = decodeURIComponent(options.scene)
    if (options.scene) {
      console.log('小程序码扫码进入')
      // that.setData({
      //   scene: decodeURIComponent(options.scene),
      //   entryType: 'scan'
      // });
    }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getImg: function(e) {
    var that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.showToast({
            title: '用户未授权',
            icon:'none'
          })
        }else{
          //执行中
          getBase64ImgData().then(res => {
            that.setData({
              img: res
            });
            that.shareImg();
          });
          //执行中
        }
      }
    });
  },
  shareImg:function(){
    var that=this;
    //执行中
    wx.showLoading({
      title: '生成中...',
    })
    wx.downloadFile({
      url: app.globalData.userInfo.avatarUrl,
      success: function (res1) {
        //console.log(res1)
        //缓存头像图片
        that.setData({
          portrait_temp: res1.tempFilePath
        })
        //缓存canvas绘制小程序二维码
        // wx.downloadFile({
        //   url: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1734347021,3188577711&fm=27&gp=0.jpg',//that.data.portrait_temp,
        //   success: function (res2) {
        //     console.log('二维码：' + res2.tempFilePath)
        //     //缓存二维码
        //     that.setData({
        //       qrcode_temp: res2.tempFilePath
        //     })
        //     console.log('开始绘制图片')
        //     that.drawImage();
        //     wx.hideLoading();
        //     setTimeout(function () {
        //       that.canvasToImage()
        //     }, 200)
        //   }
        // })
        // 缓存canvas绘制小程序二维码结束
        //缓存二维码
        that.setData({
          qrcode_temp: that.data.img
        })
        console.log('开始绘制图片')
        that.drawImage();
        wx.hideLoading();
        setTimeout(function () {
          that.canvasToImage()
        }, 200)
        //缓存二维码结束
      }
    })
          //执行中
  },
  drawImage: function() {
    console.log('绘制图片ing...')
    //绘制canvas图片
    var that = this
    const ctx = wx.createCanvasContext('myCanvas')
    var bgPath = '../../images/share_bg.png'
    var portraitPath = that.data.portrait_temp
    var hostNickname = app.globalData.userInfo.nickName

    var qrPath = that.data.qrcode_temp    
    var windowWidth = that.data.windowWidth
    console.log(windowWidth)
    console.log(that.data.windowHeight)
    that.setData({
      scale: 1.6
    })
    //绘制背景图片
    ctx.drawImage(bgPath, 0, 0, windowWidth, that.data.scale * windowWidth)

    //绘制头像
    ctx.save()
    ctx.beginPath()
    ctx.arc(windowWidth / 2, 0.32 * windowWidth, 0.15 * windowWidth, 0, 2 * Math.PI)
    ctx.clip()
    ctx.drawImage(portraitPath, 0.7 * windowWidth / 2, 0.17 * windowWidth, 0.3 * windowWidth, 0.3 * windowWidth)
    ctx.restore()
    //绘制第一段文本
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(0.037 * windowWidth)
    ctx.setTextAlign('center')
    ctx.fillText(hostNickname + ' 正在参加疯狂红包活动', windowWidth / 2, 0.52 * windowWidth)
    //绘制第二段文本
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(0.037 * windowWidth)
    ctx.setTextAlign('center')
    ctx.fillText('邀请你一起来领券抢红包啦~', windowWidth / 2, 0.57 * windowWidth)
    //绘制二维码
    ctx.drawImage(qrPath, 0.64 * windowWidth / 2, 0.75 * windowWidth, 0.36 * windowWidth, 0.36 * windowWidth)
    //绘制第三段文本
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(0.037 * windowWidth)
    ctx.setTextAlign('center')
    ctx.fillText('长按二维码领红包', windowWidth / 2, 1.36 * windowWidth)
    ctx.draw();

  },
  canvasToImage: function() {
    var that = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: that.data.windowWidth,
      height: that.data.windowWidth * that.data.scale,
      destWidth: that.data.windowWidth * 4,
      destHeight: that.data.windowWidth * 4 * that.data.scale,
      canvasId: 'myCanvas',
      success: function(res) {
        console.log('朋友圈分享图生成成功:' + res.tempFilePath)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res1) {
            console.log(res1)
          }
        })
        wx.previewImage({
          current: res.tempFilePath, // 当前显示图片的http链接
          urls: [res.tempFilePath] // 需要预览的图片http链接列表
        })
      },
      fail: function(err) {
        console.log('失败')
        console.log(err)
      }
    })
  },
  getQrcode: function (access_token){
    var that=this;
    wx.request({
      url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token,
      method:"POST",
      responseType:'arraybuffer',
      data: {
        scene:"85688",
        path:'pages/index/index',
        width:'430px',
        auto_color:true,
        line_color: { "r": "0", "g": "0", "b": "0"},
        is_hyaline:false
      },
      header:{
        'content-type':'application/json;charset=utf-8'
      },
      success(res) {
        console.log(res)
        let base64 = wx.arrayBufferToBase64(res.data);
        that.setData({
          img: "data:image/png;base64,"+base64
        });
      },
      fail(res){
        console.log(res)
      }
    })
  },
  getToken:function(){
    var that = this;
    if(that.data.accessToken){
      that.getQrcode(that.data.accessToken);
    }else{
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx85a8ff8327b8e239&secret=b2b174f766d66c0700a12b5c6033fa24',
        success(res) {
          that.getQrcode(res.data.access_token);
        }
      })
    }
  },
  onShow:function(){
    // getBase64ImgData().then(res=>{
    //   this.setData({
    //     img: res
    //   });
    // });
    console.log(this.route)
    //this.getToken()
    //获取相册授权
    // wx.getSetting({
    //   success(res) {
    //     console.log(res)
    //     if (!res.authSetting['scope.writePhotosAlbum']) {
    //       wx.authorize({
    //         scope: 'scope.writePhotosAlbum',
    //         success: function() {
    //           console.log('授权成功')
    //         },
    //         fail(res1){
    //           console.log(res1)
    //         }
    //       })
          
    //     }
    //   }
    // })
  },
  sharebtn:function(){
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  formSubmit(e) {
    console.log(e)
  }
})